import $http from '@/common/http.js'
import $store from '@/store/index.js'
/**
 * @description 数组转树型数据
 * @param {Array} data - 原始数组
 */
export const list2tree = (data, pid = null, idCol = "no", pidCol = 'parent_no') => {
  let list = []
  data.forEach(dItem => {
    // if (!dItem[pidCol]) {
    //   list.push(dItem)
    // } else 
    
    if (dItem[pidCol] === pid && dItem[idCol] !== pid) {
      dItem.text = dItem.classify_name;
      dItem.value = dItem.no
      dItem.children = list2tree(data, dItem[idCol], idCol, pidCol)
      list.push(dItem)
    }
  })

  return list
}

export const getGoods = async (cond, pageNo = 1, rownumber = 500) => {
  const url = `/retail/select/srvretail_goods_info_select`;
  const req = {
    "serviceName": "srvretail_goods_info_select",
    "colNames": ["*"],
    "condition": [{
      colName: 'sale_state',
      ruleType: 'ne',
      value: '下架'
    }],
    "page": {
      "pageNo": pageNo,
      "rownumber": rownumber
    }
  }
  if (cond) {
    req.condition = [...req.condition, ...cond]
  }
  if (Array.isArray($store?.state?.$goodsList) && $store?.state?.$goodsList.length > 0) {

  } else {
    // 第一次加载
    uni.showLoading({
      mask: true
    })
  }

  let res = await $http.post(url, req)
  if (Array.isArray(res?.data?.data) && res.data.data.length > 0) {
    try {
      let ids = res.data.data.reduce((pre, cur) => {
        if (cur.allow_member_price == '允许') {
          if (pre) {
            pre += `,${cur.goods_no}`
          } else {
            pre = cur.goods_no
          }
        }
        return pre
      }, "")
      if (ids) {
        let goodsMembers = await getGoodsMember(ids)
        if (Array.isArray(goodsMembers) && goodsMembers.length > 0) {
          // res.data.data = res.data.data.map(item => {
          //   return item
          // })
        }

        // let activites = await getActivitesGoods()
        let activites2 = await getActivitesGoods2()

        if (Array.isArray(activites2) && activites2.length > 0) {
          $store.commit('SET_ACTIVITY_LIST', activites2)
          res.data.data = res.data.data.map(item => {
            item._promotionList = activites2.filter(e => item.goods_no && item.goods_no === e.goods_no)
            return item
          })
        }
      }
    } catch (e) {
      //TODO handle the exception
    }
  }
  uni.hideLoading()
  return {
    data: res?.data?.data,
    page: res?.data?.page
  }

}

export const getGoodsMember = async (ids) => {
  let srv = 'srvretail_goods_member_select'
  srv = 'srvretail_goods_member_price_select'
  const url = `/retail/select/${srv}`
  const req = {
    "serviceName": srv,
    "colNames": ["*"],
    "condition": [{
      "colName": "goods_no",
      "ruleType": "in",
      "value": ids
    }]
  }
  const res = await $http.post(url, req)
  if (res?.data?.state === 'SUCCESS') {
    $store.commit('SET_GOODS_PRICE_LIST', res.data.data)
    return res.data.data || []
  } else {
    return []
  }
}

export const deleteGoods = async (ids) => {
  const url = '/retail/operate/srvretail_goods_info_delete'
  const req = [{
    "serviceName": "srvretail_goods_info_delete",
    "condition": [{
      "colName": "id",
      "ruleType": "in",
      "value": ids,
    }]
  }]
  const res = await $http.post(url, req)
  uni.showToast({
    title: res?.data?.resultMessage,
    icon: 'none',
    duration: 3000
  })
  return res?.data?.state === 'SUCCESS'
}


/**
 * @description 查找分类列表
 * @param {array} cond - 查询条件
 */
export const getClassify = async (cond = []) => {
  const url = '/retail/select/srvretail_goods_classify_select'
  const req = {
    "serviceName": "srvretail_goods_classify_select",
    "colNames": ["*"],
    "page": {
      "pageNo": 1,
      "rownumber": 9999
    },
    "order": []
  }
  if (Array.isArray(cond) && cond.length > 0) {
    rqe.condition = cond
  }
  const res = await $http.post(url, req)
  if (res?.data?.state === 'SUCCESS') {
    const data = res.data.data
    return list2tree(data)
  } else {
    return res?.data?.resulMessage
  }
}

/**
 * @param {number} id 
 * @param {object} data 被修改数据
 * @return {array} 更新后端数据
 */
export const updateClassify = async (id, data) => {
  const req = [{
    "serviceName": "srvretail_goods_classify_update",
    "condition": [{
      "colName": "id",
      "ruleType": "eq",
      "value": id,
    }],
    "data": [data]
  }]
  const url = `/retail/operate/srvretail_goods_classify_update`
  const res = await $http.post(url, req)
  if (res.data.state === 'SUCCESS') {
    uni.showToast({
      title: res?.data?.resultMessage,
      icon: 'none'
    })
    return await getClassify()
  } else {
    uni.showToast({
      title: res?.data?.resultMessage,
      icon: 'none'
    })
  }
}

export const deleteClassify = async (id) => {
  if (id) {
    const req = [{
      "serviceName": "srvretail_goods_classify_delete",
      "condition": [{
        "colName": "id",
        "ruleType": "eq",
        "value": id,
      }]
    }]
    const url = `/retail/operate/srvretail_goods_classify_delete`
    const res = await $http.post(url, req)

    uni.showToast({
      title: res?.data?.resultMessage,
      icon: 'none'
    })

    if (res?.data?.state === 'SUCCESS') {
      return await getClassify()
    }
  }
}

/**
 * 批量打印商品标签
 */
export const printTags = async (ids, goodsNos) => {
  const url = `/retail/operate/srvsys_label_print`
  const req = [{
    "serviceName": "srvsys_label_print",
    "data": [{
      "goods_no": goodsNos
    }],
    "srvApp": "retail",
    "condition": [{
      "colName": "id",
      "value": ids,
      "ruleType": "in"
    }]
  }]
  const {
    data
  } = await this.$http.post(url, req)
  return data
}

export const getActivitesGoods2 = async () => {

  const url = `/mkt/select/srvmkt_available_promotion_activity_select`
  const req = {
    "serviceName": "srvmkt_available_promotion_activity_select",
    "colNames": ["*"],
    "condition": [{
      colName: 'promotion_state',
      ruleType: 'eq',
      value: '生效'
    }],
    "page": {
      "pageNo": 1,
      "rownumber": 10000
    },
  }
  const res = await $http.post(url, req)
  if (res?.data?.state === 'SUCCESS' && res?.data?.data.length > 0) {
    let activites = res.data.data
    return activites
  }
}

/**
 * @description 查找营销活动商品
 * 
 */
export const getActivitesGoods = async () => {
  const url = `/mkt/select/srvmkt_promotion_activity_select`
  const req = {
    "serviceName": "srvmkt_promotion_activity_select",
    "colNames": ["*"],
    "condition": [{
      colName: 'promotion_state',
      ruleType: 'eq',
      value: '生效'
    }],
    "page": {
      "pageNo": 1,
      "rownumber": 10
    },
  }
  const res = await $http.post(url, req)
  if (res?.data?.state === 'SUCCESS' && res?.data?.data.length > 0) {
    let activites = res.data.data
    const url2 = `/mkt/select/srvmkt_promotion_goods_select`
    const req2 = {
      "serviceName": "srvmkt_promotion_goods_select",
      "colNames": ["*"],
      "condition": [{
        "colName": "promotion_no",
        "ruleType": "in",
        "value": res.data.data.map(item => item.promotion_no).toString()
      }],
      "page": {
        "rownumber": 10000,
        "pageNo": 1
      },
    }
    const res2 = await $http.post(url2, req2)
    if (res2?.data?.state === 'SUCCESS' && res2?.data?.data?.length > 0) {
      let goods = res2.data.data

      // goods = goods.map(item => {
      //   item._activites = activites.find(e => item.promotion_no === e.promotion_no)
      //   return item
      // })

      activites = activites.map(item => {
        item._goodsList = goods.filter(e => item.promotion_no === e.promotion_no)
        item.goodsList = goods.filter(e => item.promotion_no === e.promotion_no)
        item._goods_nos = item.goodsList.map(e => e.goods_no)
        return item
      })
      $store.commit('SET_ACTIVITES', activites)
      return activites
    }
  }
}
